<template>
  <div class="box">
    <div class="search-box">
      <el-tabs :value="activeName" @tab-click="tabClick">
        <el-tab-pane label="公告中心" name="1"></el-tab-pane>
        <el-tab-pane label="案例中心" name="2"></el-tab-pane>
        <el-tab-pane label="其他配置" name="3"></el-tab-pane>
      </el-tabs>
    </div>
    <!-- table -->
    <div class="page-list" v-if="activeName != '3'">
      <div class="list-top-box">
        <p class="list-top-box-left">
          已选 <span class="num">{{ multipleSelection.length }}</span>/{{ tableData.length }} 数据
        </p>
        <div class="list-top-box-right">
          <el-button type="primary"
            v-if="$isPer(permission, [activeName == '1' ? 'common_addOrUpdIntroductionAdmin' : 'common_addCaseAdmin'])"
            @click="addFunc">新增{{ activeName == '1' ? '公告' : '案例' }}</el-button>
          <el-button type="primary" v-if="$isPer(permission, [activeName == '1' ? 'ggzd' : 'alzd'])"
            :disabled="multipleSelection.length != 1" @click="setTop">{{ multipleSelection[0] ?
              multipleSelection[0].is_top == 1 ? '取消' : ''
              : '' }}置顶</el-button>
          <el-button type="primary"
            v-if="$isPer(permission, [activeName == '1' ? 'gg_updIntroductionAdmin' : 'al_updIntroductionAdmin'])"
            :disabled="multipleSelection.length != 1" @click="editFunc">编辑</el-button>
          <el-button type="danger"
            v-if="$isPer(permission, [activeName == '1' ? 'gg_delWxConfigAdmin' : 'al_delWxConfigAdmin'])" plain
            :disabled="multipleSelection.length == 0" @click="delFunc">删除</el-button>
        </div>
      </div>
      <div class="table-box" v-loading="tableLoading" v-if="activeName == '1'">
        <el-table :key="activeName" ref="table" :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="tableData" highlight-selection-row border
          @selection-change="handleSelectionChange" @row-click="handleHighlightChangeTable">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column prop="title" label="公告标题" show-overflow-tooltip>
          </el-table-column>
          <el-table-column width="100" prop="is_top" label="置顶" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.is_top == 1 ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column width="200" prop="created_at" label="创建时间" show-overflow-tooltip>
          </el-table-column>
        </el-table>
      </div>

      <div class="table-box" v-loading="tableLoading" v-if="activeName == '2'">
        <el-table :key="activeName" ref="table" :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="tableData" highlight-selection-row border
          @selection-change="handleSelectionChange" @row-click="handleHighlightChangeTable">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column prop="project_number" label="案例图片" show-overflow-tooltip>
            <template slot-scope="scope">
              <div class="img-list-box">
                <el-image class="img-box" v-for="(item, index) in scope.row.admin_case_list" :key="index"
                  :src="$fileImgFunc(item)" @click="$fileViewHandle(item)">
                </el-image>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="案例标题" show-overflow-tooltip></el-table-column>
          <el-table-column prop="brand_name" label="案例品牌" show-overflow-tooltip></el-table-column>
          <el-table-column width="100" prop="is_top" label="置顶" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.is_top == 1 ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column width="200" prop="created_at" label="创建时间" show-overflow-tooltip>
          </el-table-column>
        </el-table>
      </div>

      <div class="page-footer">
        <el-pagination class="el-pagination" @current-change="handleCurrentChange" :current-page="page" :page-size="num"
          @size-change="handleSizeChange" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>

    <div class="page-list" v-else>
      <div class="content">
        <div class="tips">首页首图</div>

        <el-upload :show-file-list="false" :auto-upload="false" class="avatar-uploader banner" accept="image/*"
          action="#" list-type="picture-card" :on-change="indexImgChange">
          <i class="el-icon-plus avatar-uploader-icon" v-if="!indexImgFile.url"></i>
          <img v-else class="index-img" :src="indexImgFile.url">
          <img class="bg-img" src="https://hzybucket.obs.cn-south-1.myhuaweicloud.com/we_chat/index_bg.png">
        </el-upload>
        <div class="tips">企业介绍</div>
        <div class="tinymce-box flex">
          <tinymce @input="tinymceInput" :value="introductionContent"></tinymce>
          <div class="html-box" v-html="introductionContent"></div>
        </div>
        <el-button type="primary" @click="addOrUpdIntroduction" :loading="pageLoading">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import Tinymce from "@/components/tinymce/tinymce";
import miniApi from '@/api/mini'
import mini from "@/api/mini";

export default {
  name: "miniProgramManagement",
  components: {
    Tinymce
  },
  data() {
    return {
      tableLoading: false,//列表loading
      tableData: [],//列表数据
      formSearch: { keyword: '' },//搜索form
      showOpne: false,//
      page: 1,
      num: 10,
      total: 0,
      multipleSelection: [],//多选数据

      activeName: '1',

      indexImgFile: {
        raw: '',
        url: ''
      },
      introductionContent: '',
      pageLoading: false,
      richText: '',
      permission: [],//操作权限
    };
  },
  watch: {},
  computed: {
  },
  activated() {
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.onSearch();
  },
  destroyed() { },
  mounted() {
    this.getList();
    this.$getHtmlAuthority(this.$route.path).then(res => {
      console.log(res, "getHtmlAuthority");
      this.permission = res.data.permission;
    })
  },
  methods: {
    // 单页数据量修改
    handleSizeChange(e) {
      console.log(e)
      this.num = e;
      this.onSearch(1);
    },
    // 搜索
    onSearch(page) {
      this.page = typeof page == 'number' ? page : this.page;
      this.getList();
    },
    // 翻页
    handleCurrentChange(page) {
      this.onSearch(page);
    },
    // tab切换
    tabClick(e) {
      if (this.activeName == e.paneName) return
      this.activeName = e.paneName
      if (this.activeName == '3') {
        this.getCarouselImageAdmin()
      } else {
        this.handleSizeChange(this.num)
      }
    },
    addFunc() {
      if (this.activeName == '1') {
        this.$router.push({
          path: '/miniProgram/addNotice'
        });
      } else {
        this.$router.push({
          path: '/miniProgram/addCase'
        });
      }
    },
    editFunc() {
      let multipleSelection = this.multipleSelection;
      let item = multipleSelection[0]
      console.log(multipleSelection)
      if (this.activeName == '1') {
        this.$router.push({
          path: "/miniProgram/addNotice?sn=" + item.id,
          query: {
            route_title: '编辑公告'
          }
        })
      } else {
        this.$router.push({
          path: "/miniProgram/addCase?sn=" + item.id,
          query: {
            route_title: '编辑案例'
          }
        })
      }
    },
    setTop() {
      let multipleSelection = this.multipleSelection;
      let item = multipleSelection[0]
      let name = this.activeName == '1' ? '公告' : '案例'
      this.$confirm(item.is_top == 1 ? `您确定要取消置顶该${name}？` : `您确定要置顶该${name}？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        miniApi.setTopAdmin({
          id: item.id,
          is_top: item.is_top == 1 ? 0 : 1
        }).then(res => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            this.onSearch();
          }
        })
      })

    },
    delFunc() {
      let multipleSelection = this.multipleSelection;
      let id_arr = multipleSelection.map(item => item.id)
      let name_arr = multipleSelection.map(item => item.title)
      this.$confirm('是否删除【' + name_arr.join(', ') + '】?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        console.log(id_arr)
        miniApi.delWxConfigAdmin({
          id_arr
        }).then(res => {
          console.log(res, "setRoleDel");
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.onSearch();
          } else {
            this.$message.error(res.message);
          }
        })
      }).catch(() => { });

    },
    handleSelectionChange(e) {
      console.log(e);
      this.multipleSelection = e;
    },
    handleHighlightChangeTable(row) {
      if (!row.disabled) {
        this.$refs.table.toggleRowSelection(row);
      }
    },

    // 获取列表数据
    getList() {
      console.log(123123123123)
      this.tableLoading = true;
      let request = null
      if (this.activeName == '1') {
        request = miniApi.getNoticeList({
          page: this.page,
          num: this.num,
        })
      } if (this.activeName == '2') {
        request = miniApi.getCaseList({
          page: this.page,
          num: this.num,
        })
      }
      request.then((res) => {
        console.log(res, "获取列表");
        this.tableLoading = false;
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.max;
        }
      }).catch((err) => {
        this.$message({
          message: err.message,
          type: "warning",
        });
      });
    },
    // 获取首页/企业介绍
    getCarouselImageAdmin() {
      miniApi.getCarouselImageAdmin().then((res) => {
        console.log(res, 'getCarouselImageAdmin')
        if (res.code == 200) {
          this.indexImgFile.url = res.data.file_url
          this.introductionContent = res.data.content
          this.richText = res.data.content;
        }
      })
    },

    // 其他配置
    indexImgChange(e) {
      console.log(e)
      this.indexImgFile = e
    },
    tinymceInput(e) {
      const regex = new RegExp('img', 'gi')
      e = e.replace(regex, `img style="max-width:100%;object-fit: cover;"`)
      this.richText = e;
    },
    // 首图和企业介绍保存
    addOrUpdIntroduction() {
      this.pageLoading = true;
      let obj = {
        content: this.richText
      }
      let newFormData = new FormData();
      if (this.indexImgFile.raw) {
        newFormData.append('carousel_image', this.indexImgFile.raw);
      }
      // 添加
      newFormData.append('data', JSON.stringify(obj));
      miniApi.addCarouselImageAdmin(newFormData).then((res) => {
        console.log(res, 'addCarouselImageAdmin')
        this.pageLoading = false;
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      }).catch(err => {
        this.pageLoading = false;
      })
    }
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
@import '@/styles/listPage.scss';
</style>